package com.hrhx.bean.uom;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hrhx.bean.UnitOfMeasure;
/**
    @Author duhongming
    @Email 935720334@qq.com
    @Date 2018/1/10 10:44
*/
public class UOM {
	
	private static final Logger log = LoggerFactory.getLogger(UOM.class);
	
	/**
	 * 保留整数（四舍五入）
	 */
	public static final String ROUNDING = "#";
	/**
	 * 保留一位小数（四舍五入）
	 */
	public static final String ROUNDING1 = "#.0";
	/**
	 * 保留两位小数（四舍五入）
	 */
	public static final String ROUNDING2 = "#.00";
	/**
	 * 保留三位小数（四舍五入）
	 */
	public static final String ROUNDING3 = "#.000";
	/**
	 * 保留四位小数（四舍五入）
	 */
	public static final String ROUNDING4 = "#.0000";

	
	public  Map<String,UnitOfMeasure> unitOfMeasureMap = new HashMap<String,UnitOfMeasure>();
	
	static Number factor=1.0;
	
	public void unitOfMeasure(String reference,String name){
		log.info("---查找单位开始---");
		log.info("---reference:{},name:{}---",reference,name);
		UnitOfMeasure unitOfMeasure = unitOfMeasureMap.get(name);
		if(unitOfMeasure.getName().equals(reference)) {
			return;
		}else {
			factor = factor.doubleValue()*unitOfMeasure.getUnitMethodType().getFactor().doubleValue();
			unitOfMeasure(reference,unitOfMeasure.getReference());
		}
		log.info("factor：{}",factor);
		log.info("---查找单位结束---");
	}
	
	public String unitOfMeasureNumber(Number num,String reference,String name,String format) {
		try {
			log.info("大单位到小单位转换");
			unitOfMeasure(reference,name);
			Number factorTemp = factor;
			factor = 1.0;
			return new DecimalFormat(format).format(num.doubleValue()/factorTemp.doubleValue());
		}catch(NullPointerException e) {
			log.info("小单位到大单位转换");
			factor = 1.0;
			unitOfMeasure(name,reference);
			Number factorTemp = factor;
			factor = 1.0;
			return new DecimalFormat(format).format(num.doubleValue()*factorTemp.doubleValue());
		}
	}
	
	public String unitOfMeasureString(Number num,String reference,String name,String format) {
		UnitOfMeasure unitOfMeasure = unitOfMeasureMap.get(name);
		return unitOfMeasureNumber(num,reference,name,format)+" "+unitOfMeasure.getAbbreviation();
	}
}
